package org.aseclipse.osgi.container;

import java.net.URL;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.BundleListener;
import org.osgi.framework.ServiceReference;

public class ASBundleListener implements BundleListener {

	private static final Log log_ = LogFactory.getLog(ASBundleListener.class);
	
	public void bundleChanged(BundleEvent event) {
		Bundle bundle = event.getBundle();
		int type = bundle.getState();
		if(log_.isDebugEnabled())
			log_.debug("Process ASBundle: "+bundle.getSymbolicName() + ", type: " + event.getType()+ ", bundle state: " + type);
		if(type == BundleEvent.RESOLVED) {
			if(log_.isDebugEnabled())
				log_.debug("Process ASBundle: "+bundle.getSymbolicName());
			if(containASResource(bundle)) {
				ServiceReference refer = bundle.getBundleContext().getServiceReference(IASBundleManager.class.getName());
				IASBundleManager service = null;
				try {
					service = (IASBundleManager) bundle.getBundleContext().getService(refer);
					service.process(bundle);
				} catch(Exception ex) {
					log_.warn("Fail to handle "+bundle.getSymbolicName(), ex);
				}
			}
		}
	}
	
	private boolean containASResource(Bundle bundle) {
		try {
			URL url = bundle.getResource(ASBundle.PLUGIN_NAME);
			if(url == null)
				return false;
			else
				return true;
		} catch(Exception ex) {
		}
		return false;
	}

}
